package com.wiki.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wiki.entity.User;
import com.wiki.entity.User;
import com.wiki.except.BusinessException;
import com.wiki.except.BusinessExceptionCode;
import com.wiki.mapper.UserMapper;
import com.wiki.mapper.UserMapper;
import com.wiki.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wiki.utils.CopyUtil;
import com.wiki.utils.SnowFlake;
import com.wiki.utils.commonRequest.user.UserLoginReq;
import com.wiki.utils.commonRequest.user.UserQueryReq;
import com.wiki.utils.commonRequest.user.UserResetPasswordReq;
import com.wiki.utils.commonRequest.user.UserSaveReq;
import com.wiki.utils.commonResponse.UserLoginResp;
import com.wiki.utils.commonResponse.UserQueryResp;
import com.wiki.utils.commonResponse.PageResp;
import lombok.extern.java.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author 偷闰土的猹
 * @since 2022-01-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SnowFlake snowFlake;
    private static final Logger LOG = LoggerFactory.getLogger(UserService.class);

    @Override
    public PageResp<UserQueryResp> listAll(UserQueryReq req) {
        PageResp<UserQueryResp> resp = new PageResp<>();

        PageHelper.startPage(req.getPage(), req.getSize());
        List<User> users;
        if (ObjectUtils.isNotEmpty(req.getLoginName())) {
            QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("login_name", req.getLoginName());

            users = userMapper.selectList(wrapper);

        } else {
            users = userMapper.selectList(null);
        }
        System.out.println(users.toString());
        List<UserQueryResp> userQueryResps = CopyUtil.copyList(users, UserQueryResp.class);


        resp.setList(userQueryResps);

        return resp;
    }

    @Override
    public void save(UserSaveReq req) {
        User copy = CopyUtil.copy(req, User.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            //新增
            User user = selectByLoginName(req.getLoginName());
            if (ObjectUtils.isEmpty(user)) {
                Long id = snowFlake.nextId();
                copy.setId(id);
                userMapper.insert(copy);
            } else {
                //用户名已存在
                throw new BusinessException(BusinessExceptionCode.USER_LOGIN_NAME_EXIST);
            }
        } else {
            //更新
            copy.setLoginName(null); //防止前端绕过disabled进行查询
            copy.setPassword(null);//修改时，不应该修改密码
            userMapper.updateById(copy);
        }
    }

    @Override
    public void delete(Long id) {
        int i = userMapper.deleteById(id);
        if (i > 0)
            System.out.println("删除了：" + id);
        else
            System.out.println("删除失败！id为：" + id);
    }

    @Override
    public PageResp<UserQueryResp> queryLike(UserQueryReq req) {
        PageResp<UserQueryResp> respList = new PageResp<>();
        PageHelper.startPage(req.getPage(), req.getSize());
        QueryWrapper<User> wrapper = new QueryWrapper<User>().like("login_name", req.getLoginName());
        List<User> users = userMapper.selectList(wrapper);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        respList.setTotal(pageInfo.getTotal());
        List<UserQueryResp> respList1 = CopyUtil.copyList(users, UserQueryResp.class);
        respList.setList(respList1);

        return respList;
    }

    @Override
    public User selectByLoginName(String loginName) {
        Wrapper<User> wrapper = new QueryWrapper<User>().eq("login_name", loginName);
        User user = userMapper.selectOne(wrapper);
        return user;
    }

    @Override
    public void resetPassword(UserResetPasswordReq req) {
        User copy = CopyUtil.copy(req, User.class);
        userMapper.updateById(copy);
    }

    @Override
    public UserLoginResp login(UserLoginReq req) {

        User userDB = selectByLoginName(req.getLoginName());

        if (ObjectUtils.isEmpty(userDB)) {
//            用户名不存在
            LOG.info("用户名不存在，{}", req.getLoginName());
            throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
        } else {
            if (userDB.getPassword().equals(req.getPassword())) {
//                登录成功
                UserLoginResp userLoginResp = CopyUtil.copy(userDB, UserLoginResp.class);
                return userLoginResp;
            } else {
//                密码错误
                LOG.info("密码错误,输入密码：{},数据库密码：{}", req.getPassword(), userDB.getPassword());
                throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
            }
        }
    }


}
